import { isPlainObject, deepMerge } from './util'
import { Method } from '../types'

/**
 * 描述 辅助函数，规范化Headers
 * @param {any} headers
 * @param {string} normalizeName  规范字段
 * @returns {void}
 */
function normalizeHeaderName(headers: any, normalizeName: string): void {
  if (!headers) {
    return
  }
  Object.keys(headers).forEach((key) => {
    if (key !== normalizeName && key.toUpperCase() === normalizeName.toUpperCase()) {
      headers[normalizeName] = headers[key]
      delete headers[key]
    }
  })
}

/**
 * 描述 对Header的content-type字段做处理做处理
 * @param {any} headers
 * @param {any} data
 * @returns {any}
 */
export function processHeaders(headers: any, data: any): any {
  normalizeHeaderName(headers, 'Content-Type')

  // 判断是否有自定义Header
  if (isPlainObject(data)) {
    if (headers && !headers['Content-Type']) {
      headers['Content-Type'] = 'application/json;charset=utf-8'
    }
  }

  return headers
}

/**
 * 描述 解析响应头
 * @param {string} headers
 * @returns {any}
 */
export function parseHeaders(headers: string): any {
  let parsed = Object.create(null)
  if (!headers) {
    return
  }
  headers.split('\r\n').forEach((line) => {
    let [key, val] = line.split(':')
    key = key.trim().toLowerCase()
    if (!key) {
      return
    }
    if (val) {
      val = val.trim()
    }
    parsed[key] = val
  })

  return parsed
}

/**
 * 描述 提取header字段
 * @param {any} headers
 * @param {Method} method
 * @returns {any}
 */
export function flattenHeaders(headers: any, method: Method): any {
  if (!headers) {
    return
  }
  headers = deepMerge(headers.common, headers[method], headers)

  const methodsReadyDelete = [
    'get',
    'post',
    'delete',
    'put',
    'options',
    'head',
    'patch',
    'options',
    'common',
  ]

  methodsReadyDelete.forEach((method) => {
    delete headers[method]
  })

  return headers
}
